package com.example.demo.utils;

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Created by jhx on 2018/5/5.
 * 利用HttpClient进行post请求的工具类(用于key-value格式的参数)
 */
public class HttpClientUtil {
    public final static String defaultUrlEncoding = HTTP.UTF_8;//默认编码格式

    public String doPost(String url,Map<String,String> map,String charset){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while(iterator.hasNext()){
                Entry<String,String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
            }
            if(list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    public static String loadMessageByPost(String url, String contentType,List<NameValuePair> entity) throws IOException {
        return loadMessageByPost(url, defaultUrlEncoding, contentType, entity);
    }

    public static String postHttpRequestString(String url,String body) throws IOException {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//超时时间毫秒
        HttpPost httpPost = new HttpPost(url);

        StringEntity stringEntity = new StringEntity(body, Charset.forName("UTF-8"));
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");

        HttpResponse response = client.execute(httpPost);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
        String line;
        StringBuffer jsonString = new StringBuffer();
        while((line = bufferedReader.readLine()) != null) {
            jsonString.append(line);
        }
        return jsonString.toString();
    }

    public static String postHttpRequestStringUrlencoded(String url,String body) throws IOException {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//超时时间毫秒
        HttpPost httpPost = new HttpPost(url);

        StringEntity stringEntity = new StringEntity(body, Charset.forName("UTF-8"));
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        HttpResponse response = client.execute(httpPost);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
        String line;
        StringBuffer jsonString = new StringBuffer();
        while((line = bufferedReader.readLine()) != null) {
            jsonString.append(line);
        }
        return jsonString.toString();
    }



    public static List<String> postHttpRequestByte(String url,String body) throws IOException {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//超时时间毫秒
        HttpPost httpPost = new HttpPost(url);

        StringEntity stringEntity = new StringEntity(body, Charset.forName("UTF-8"));
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");

        HttpResponse response = client.execute(httpPost);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
        String line;
        List<String> list=new ArrayList<String>();
        while((line = bufferedReader.readLine()) != null) {
            list.add(line);
        }
        return list;
    }

    public static String doPost(String url, String params) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
            else{
                System.out.println("请求返回:"+state+"("+url+")");
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String loadMessageByPost(String url, String urlEncoding, String contentType,  List<NameValuePair> entity) throws IOException {

        String result = null;//返回结果
        HttpClient httpClient = null;
        HttpPost post = null;
        BufferedReader reader = null;
        try {
            if (!url.isEmpty()) {
                urlEncoding = (urlEncoding==null ? defaultUrlEncoding : urlEncoding);
                httpClient = initHttpClient();//初始化 httpClient
                post = new HttpPost(url);//创建 post
                post.setHeader("Content-Type",contentType);
                post.setEntity(new UrlEncodedFormEntity(entity,HTTP.UTF_8));
                //post.setEntity(entity);
			/*
			ArrayList<NameValuePair> nvps = new ArrayList<NameValuePair>();//创建参数容器
			for (Map.Entry<String, Object> entry : params.entrySet()) {//组装参数
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
			}
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			multipartEntityBuilder.addPart("file1",new FileBody(new File("/Users/WILL/Desktop/JPA.png")));
			multipartEntityBuilder.addBinaryBody("file2", new File("/Users/WILL/Desktop/问题.docx"), ContentType.MULTIPART_FORM_DATA,"问题.docx");
			multipartEntityBuilder.addTextBody("test","test2");
			post.setEntity(multipartEntityBuilder.build());
			post.setEntity(new FileEntity(new File("/")));
			post.setEntity(new StringEntity(JSON.toJSON(params)));
			post.setEntity(new UrlEncodedFormEntity(nvps, urlEncoding));
			*/
                HttpResponse response = httpClient.execute(post);
                StringBuffer stringBuffer = new StringBuffer();
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), urlEncoding));
                    String content = null;
                    while ((content = reader.readLine()) != null) {
                        stringBuffer.append(content);
                    }
                }
                result = stringBuffer.toString();
            }
        } finally {
            if (reader != null) {
                reader.close();
                reader = null;
            }
            if (post != null && !post.isAborted()) {
                post.abort();
                post = null;
            }
            if (httpClient != null) {
                httpClient.getConnectionManager().shutdown();
                httpClient = null;
            }
        }
        return result;
    }

    public static HttpClient initHttpClient() {
        HttpClient httpClient = null;
        httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); //请求超时 单位毫秒
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);//读取超时
        return httpClient;
    }

}
